/**
 * @FileName			LoginFilter.java
 * @Author				BOCAI
 * @Version				V1.0
 * @CreateTime		2017年4月22日		下午7:35:32
 * @Copyright			Copyright(C) 2016-2017 All rights Reserved, Designed By BOCAI
 */
package com.like.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.like.common.ContextArgument;


/**
 * @ClassName			LoginFilter
 * @Description			用户登录验证的过滤器
 * @Author					BOCAI
 * @CreateTime			2017年4月22日		下午7:35:32
 * @Version					V1.0
 * @History
 * Date         Author        Version        Discription
 * ---------------------------------------------------------------------------
 * 2017年4月22日     	BOCAI      	1.0             1.0
 *
 * Why & What is modified:
 *
 */
public class LoginFilter implements Filter {

	/**
	 * 过滤器配置参数的管理器
	 */
	private FilterConfig config ;

	@Override
	public void destroy() {

	}

	/**
	 *
	 * 	判断当前地址是否包含免登录验证的地址
	 * @param url							当前地址
	 * @param nonvalidateUrl		免登录验证的地址集,格式：XXX.YY ; XXX.YY
	 * @return								如果包含返回true,否则返回false
	 */
	private boolean contain(String url , String nonvalidateUrl ){
		boolean result = false ;
		String[] items = nonvalidateUrl.split(";") ;
		int length = items.length;

		for( int index = 0 ; index < length ; index++ ){

			if(url.indexOf(items[index].trim()) > 0 ){
				result = true ;
				return result ;
			}
		}

		return result ;
	}


	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
		String nonValiteUrl = config.getInitParameter("nonValiteUrl");
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		String failPath = request.getContextPath()+ config.getInitParameter("failPath");
		String url = request.getRequestURI();

		if( this.contain(url, nonValiteUrl) ){
			arg2.doFilter(arg0, arg1);
			return ;
		}

		HttpSession session  = request.getSession();

		if( session.getAttribute(ContextArgument.UID) != null ){
			arg2.doFilter(arg0, arg1);

		}else{
			response.sendRedirect(failPath);
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.config = arg0 ;

	}

}
